import {take, call, put, fork, cancel } from 'redux-saga/effects';
import { hashHistory } from 'react-router'
import AuthManager from '../services/auth'
import * as Actions from '../actions/index'
import * as Types from '../actions/ActionTypes.js'
import * as api from '../services/user';
import {message} from 'antd';
import callServiceApi from './utils';

// 手机/邮箱 登录
function* watchLogin() {
  while (true) {
    const {payload} = yield take(Types.USER_LOGIN.REQUEST);
    yield fork(userLogin, payload);
    const action = yield take([Types.USER_LOGIN.SUCCESS, Types.USER_LOGIN.FAILURE])
    if(action.type == Types.USER_LOGIN.SUCCESS) {
      AuthManager.setToken(action.payload.subject);
      hashHistory.push('/');
    }
  }
}

// 退出
function* watchLogout() {
  while (true) {
    yield take(Types.USER_LOGOUT.REQUEST);
    if (AuthManager.loggedIn()) {
      yield fork(userLogout);
      const action = yield take([Types.USER_LOGOUT.SUCCESS, Types.USER_LOGOUT.FAILURE])
      AuthManager.logout();
      //To login
    }
    hashHistory.push('/login');
  }
}

// 获取菜单
function* watchMenu() {
  while (true) {
    yield take(Types.USER_MENU.REQUEST);
    yield fork(userMenu);
  }
}

// 检查token
function* watchCheckToken() {
  while (true) {
    yield take(Types.CHECK_TOKEN.REQUEST);
    if (AuthManager.loggedIn()) {
      yield fork(checkToken);
      const action = yield take([Types.CHECK_TOKEN.SUCCESS, Types.CHECK_TOKEN.FAILURE]);

      if(action.type == Types.CHECK_TOKEN.FAILURE) {
        AuthManager.logout();
        hashHistory.push('/login');
      } else {
        //发起获取用户信息
        yield put(Actions.userLogin.request()({"email":"111111", "password":"1111111"}));
      }

    }
  }
}

function* userLogin(payload) {
  yield fork(callServiceApi, Actions.userLogin, api.login, payload);
}

function* checkToken() {
  yield fork(callServiceApi, Actions.checkToken, api.checkToken, {}, false);
}

function* userLogout() {
  yield fork(callServiceApi, Actions.userLogout, api.logout, {});
}

function* userMenu() {
  yield fork(callServiceApi, Actions.userMenu, api.menu, {});
}

export default function*() {
  yield [
    fork(watchLogin),
    fork(watchMenu),
    fork(watchLogout),
    fork(watchCheckToken),
  ];
  yield put(Actions.checkToken.request()());
}
